package com.llg.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.llg.mapper.SupplySpecMapper;
import com.llg.model.code.CommonCode;
import com.llg.model.code.PageCode;
import com.llg.model.response.*;
import com.llg.pojo.SupplySpec;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
public class SupplySpecService {
    @Autowired
    private SupplySpecMapper supplySpecMapper;

    //通过电源品牌id查询所有型号
    public PageResult<SupplySpec> findByBrandId(int bid){
        Example example = new Example(SupplySpec.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("bid", bid);
        List<SupplySpec> supplySpecs = supplySpecMapper.selectByExample(example);
        return new PageResult<>(CommonCode.SUCCESS, 1,1, supplySpecs);
    }

    //搜索并分页的查询
    public PageResult<SupplySpec> findList(int currentPage,int pageSize,SupplySpec supplySpec){
        //判断参数是否合法
        if (currentPage <= 0) return new PageResult<>(PageCode.PAGE_ERR1, 0, 0, null);
        if (pageSize <= 0) return new PageResult<>(PageCode.SIZE_ERR, 0, 0, null);
        PageHelper.startPage(currentPage, pageSize);
        Example example = new Example(SupplySpec.class);
        Example.Criteria criteria = example.createCriteria();
        if (supplySpec != null) {
            if (supplySpec.getName() != null && !supplySpec.getName().equals("")) {
                criteria.andLike("name", "%" + supplySpec.getName() + "%");
            }
        }
        List<SupplySpec> supplySpecs = supplySpecMapper.selectByExample(example);
        PageInfo<SupplySpec> page = new PageInfo<>(supplySpecs);
        return new PageResult<>(CommonCode.SUCCESS, (int)page.getTotal(), page.getPages(), page.getList());
    }

    //通过id查询
    public DataResult<SupplySpec> findById(int id){
        return new DataResult<>(CommonCode.SUCCESS, supplySpecMapper.selectByPrimaryKey(id));
    }

    //增
    public DataResult<SupplySpec> add(SupplySpec supplySpec){
        supplySpec.setElectric(supplySpec.getPower() / supplySpec.getVoltage());
        supplySpecMapper.insertSelective(supplySpec);
        return new DataResult<>(CommonCode.SUCCESS, supplySpec);

    }

    //删
    public ResponseResult delete(int id){
        supplySpecMapper.deleteByPrimaryKey(id);
        return new ResponseResult(CommonCode.SUCCESS);
    }

    //改
    public ResponseResult update(SupplySpec supplySpec){
        supplySpec.setElectric(supplySpec.getPower() / supplySpec.getVoltage());
        supplySpecMapper.updateByPrimaryKeySelective(supplySpec);
        return new ResponseResult(CommonCode.SUCCESS );
    }
}
